package com.lzx.iteam;

import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.os.Bundle;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import com.baidu.mapapi.SDKInitializer;
import com.baidu.mapapi.map.*;
import com.baidu.mapapi.model.LatLng;
import com.lzx.iteam.base.FindViewById;
import com.lzx.iteam.base.MyBaseActivity;
import com.lzx.iteam.bean.LegworkRecordData;
import com.lzx.iteam.util.Constants;
import com.lzx.iteam.util.DateUtil;

import java.util.ArrayList;
import java.util.List;


/**
 * Created by Megan on 16/9/2.
 */
public class LegworkMapRecordActivity extends MyBaseActivity implements ViewPager.OnPageChangeListener, View.OnClickListener {
    @FindViewById(id = R.id.title_tv_right)
    private TextView mTvRight;
    @FindViewById(id = R.id.title_tv_center)
    private TextView mTvTitle;
    @FindViewById(id = R.id.title_ll_back)
    private LinearLayout mLayoutBack;
    @FindViewById(id = R.id.ll_legwork_record_no_data_layout)
    private LinearLayout mLlNoData;
    @FindViewById(id = R.id.tv_legwork_record_no_data_text)
    private TextView mTvNoData;
    @FindViewById(id = R.id.vp_legwork_record_pager)
    private ViewPager mViewPager;
    @FindViewById(id = R.id.ll_legwork_record_dots)
    private LinearLayout mLlDots;
    @FindViewById(id = R.id.mv_legwork_record_mapview)
    private MapView mMapView;
    BaiduMap mBaiduMap;

    private Polyline mPolyline;
    private Marker mMarker;
    private OverlayOptions markerOptions;
    private ArrayList<View> viewList;
    private int position;
    private ImageView[] mImageViews;
    private ArrayList<LegworkRecordData> recordDatas;


    protected void onCreate(Bundle savedInstanceState) {
        SDKInitializer.initialize(getApplicationContext());

        super.onCreate(savedInstanceState, R.layout.legwork_map_record_layout);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.title_ll_back:
                finish();
                break;
        }
    }

    @Override
    public void initListener() {
        mViewPager.setOnPageChangeListener(this);
        mLayoutBack.setOnClickListener(this);
        mBaiduMap.setOnMarkerClickListener(new BaiduMap.OnMarkerClickListener() {
            @Override
            public boolean onMarkerClick(Marker marker) {
                for (int i = 0; i < recordDatas.size(); i++) {
                    if (marker.getPosition().equals(recordDatas.get(i).getLatLng())) {
                        mViewPager.setCurrentItem(i);
                    }
                }
                return false;
            }
        });

    }

    @Override
    public void initData() {
        recordDatas = new ArrayList<LegworkRecordData>();
        Intent intent = getIntent();
        recordDatas.addAll((ArrayList<LegworkRecordData>) intent.getSerializableExtra("recordData"));
        mTvTitle.setText("地图轨迹");

        initMap();
        drawPolyLine();
        viewList = new ArrayList<View>();
        mImageViews = new ImageView[recordDatas.size()];
        if (recordDatas.size() > 0) {
            mLlNoData.setVisibility(View.GONE);
            mViewPager.setVisibility(View.VISIBLE);
            mLlDots.setVisibility(View.VISIBLE);
        } else {
            mLlNoData.setVisibility(View.VISIBLE);
            mViewPager.setVisibility(View.GONE);
            mLlDots.setVisibility(View.GONE);
        }
        for (int i = 0; i < recordDatas.size(); i++) {
            View view = getLayoutInflater().from(this).inflate(R.layout.legwork_record_viewpager_item, null);
            TextView num = (TextView) view.findViewById(R.id.tv_legwork_record_pager_num);
            TextView time = (TextView) view.findViewById(R.id.tv_legwork_record_pager_time);
            TextView address = (TextView) view.findViewById(R.id.tv_legwork_record_pager_address);
            num.setText(i + 1 + "");
            time.setText(DateUtil.getHourAndMin(Long.parseLong(recordDatas.get(i).getTime()) * 1000));
            address.setText(recordDatas.get(i).getAddress());
            viewList.add(view);
            ImageView imageView = new ImageView(LegworkMapRecordActivity.this);
            LinearLayout.LayoutParams vl = new LinearLayout.LayoutParams(Constants.dip2px(this, 5), Constants.dip2px(this, 5));
            vl.setMargins(9, 0, 9, 0);
            imageView.setLayoutParams(vl);

            mImageViews[i] = imageView;
            if (i == 0) {
                mImageViews[i].setBackgroundResource(R.drawable.blue_dot_selected);
            } else {
                mImageViews[i].setBackgroundResource(R.drawable.blue_dot_normal);
            }
            mLlDots.addView(mImageViews[i]);
        }
        mViewPager.setAdapter(pagerAdapter);

    }

    private void initMap() {
        mBaiduMap = mMapView.getMap();
        //设置是否显示比例尺控件
        mMapView.showScaleControl(false);
        //设置是否显示缩放控件
        mMapView.showZoomControls(false);
        // 删除百度地图LoGo
        mMapView.removeViewAt(1);
//        UiSettings settings = mBaiduMap.getUiSettings();
//        settings.setAllGesturesEnabled(false);   //关闭一切手势操作
//        settings.setOverlookingGesturesEnabled(false);//屏蔽双指下拉时变成3D地图
//        settings.setZoomGesturesEnabled(true);//获取是否允许缩放手势返回:是否允许缩放手势

        MapStatus.Builder builder = new MapStatus.Builder();
        builder.target(new LatLng(40.067187, 116.427047)).zoom(16.0f);
        mBaiduMap.setMapStatus(MapStatusUpdateFactory.newMapStatus(builder.build()));


    }


    private void drawPolyLine() {
        mBaiduMap.clear();
        List<LatLng> polylines = new ArrayList<LatLng>();
        for (int i = 0; i < recordDatas.size(); i++) {
            LatLng latLng = new LatLng(recordDatas.get(i).getLatitude(), recordDatas.get(i).getLongitude());
            recordDatas.get(i).setLatLng(latLng);
            polylines.add(latLng);
            View view = LayoutInflater.from(this).inflate(R.layout.legwork_map_record_icon, null);
            TextView textView = (TextView) view.findViewById(R.id.tv_legwork_map_record_icon);
            if (position == i) {
                textView.setBackgroundDrawable(getResources().getDrawable(R.drawable.legwork_map_record_icon2));
                LatLng cenpt = latLng;
                //定义地图状态
                MapStatus mMapStatus = new MapStatus.Builder()
                        .target(cenpt)
                        .zoom(16)
                        .build();
                //定义MapStatusUpdate对象，以便描述地图状态将要发生的变化
                MapStatusUpdate mMapStatusUpdate = MapStatusUpdateFactory.newMapStatus(mMapStatus);
                //改变地图状态
                mBaiduMap.setMapStatus(mMapStatusUpdate);
            } else {
                textView.setBackgroundDrawable(getResources().getDrawable(R.drawable.legwork_map_record_icon1));
            }
            textView.setText(i + 1 + "");
            markerOptions = new MarkerOptions().flat(true).anchor(0.5f, 0.5f)
                    .icon(BitmapDescriptorFactory.fromBitmap(getViewBitmap(view))).position(polylines.get(i));
            mMarker = (Marker) mBaiduMap.addOverlay(markerOptions);
        }

        if (polylines.size() > 1) {
            PolylineOptions polylineOptions = new PolylineOptions().points(polylines).width(6).color(Color.RED);
            mPolyline = (Polyline) mBaiduMap.addOverlay(polylineOptions);
        }


    }


    private Bitmap getViewBitmap(View addViewContent) {

        addViewContent.setDrawingCacheEnabled(true);

        addViewContent.measure(
                View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED),
                View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED));
        addViewContent.layout(0, 0,
                addViewContent.getMeasuredWidth(),
                addViewContent.getMeasuredHeight());

        addViewContent.buildDrawingCache();
        Bitmap cacheBitmap = addViewContent.getDrawingCache();
        Bitmap bitmap = Bitmap.createBitmap(cacheBitmap);

        return bitmap;
    }


    @Override
    protected void onResume() {
        super.onResume();
        mMapView.onResume();
    }

    @Override
    protected void onPause() {
        super.onPause();
        mMapView.onPause();
    }


    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        mMapView.onSaveInstanceState(outState);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        mMapView.onDestroy();
        mBaiduMap.clear();
    }


    PagerAdapter pagerAdapter = new PagerAdapter() {

        @Override
        public boolean isViewFromObject(View arg0, Object arg1) {

            return arg0 == arg1;
        }

        @Override
        public int getCount() {

            return viewList.size();
        }

        @Override
        public void destroyItem(ViewGroup container, int position,
                                Object object) {
            container.removeView(viewList.get(position));

        }

        @Override
        public int getItemPosition(Object object) {

            return super.getItemPosition(object);
        }


        @Override
        public Object instantiateItem(ViewGroup container, int position) {
            container.addView(viewList.get(position));
            return viewList.get(position);
        }

    };

    @Override
    public void onPageScrolled(int i, float v, int i1) {

    }

    @Override
    public void onPageSelected(int i) {
        position = i;
        for (int j = 0; j < recordDatas.size(); j++) {
            if (i != j) {
                mImageViews[j].setBackgroundResource(R.drawable.blue_dot_normal);
            } else {
                mImageViews[i].setBackgroundResource(R.drawable.blue_dot_selected);
            }
        }
        drawPolyLine();

    }

    @Override
    public void onPageScrollStateChanged(int i) {

    }
}
